package com.sk.waste.app.views;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.widget.ImageView;

import com.sk.waste.app.R;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;

@SuppressLint("AppCompatCustomView")
public class RoundImageView extends ImageView
  {
    // 默认圆角半径
    private static final int DEFAULT_RADIUS = 0;

    // 圆角半径
    private int mRadius;
    // 画笔
    private Paint mPaint;
    // 圆角矩形区域
    private RectF mRectF;

    public RoundImageView(Context context)
      {
        this(context, null);
      }

    public RoundImageView(Context context, @Nullable AttributeSet attrs)
      {
        this(context, attrs, 0);
      }

    public RoundImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr)
      {
        super(context, attrs, defStyleAttr);

        // 初始化属性
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.lc_rounded_imageview);
        mRadius = ta.getDimensionPixelSize(R.styleable.lc_rounded_imageview_radius, DEFAULT_RADIUS);
        ta.recycle();

        init();
      }

    private void init()
      {
        // 初始化画笔
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));

        // 初始化矩形区域
        mRectF = new RectF();
      }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom)
      {
        super.onLayout(changed, left, top, right, bottom);
        // 更新矩形区域
        mRectF.set(0, 0, getWidth(), getHeight());
      }

    @Override
    protected void onDraw(Canvas canvas)
      {
        // 保存图层
        int saveLayer = canvas.saveLayer(mRectF, null, Canvas.ALL_SAVE_FLAG);

        // 绘制原始图像
        super.onDraw(canvas);

        // 绘制圆角矩形，实现圆角效果
        canvas.drawRoundRect(mRectF, mRadius, mRadius, mPaint);

        // 恢复图层
        canvas.restoreToCount(saveLayer);
      }

    /**
     * 设置圆角半径
     *
     * @param radius 圆角半径，单位为像素
     */
    public void setRadius(int radius)
      {
        mRadius = radius;
        invalidate();
      }

    /**
     * 获取当前圆角半径
     *
     * @return 圆角半径，单位为像素
     */
    public int getRadius()
      {
        return mRadius;
      }

  }
